<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

class RequestLogMiddleware
{
    public function handle($request, Closure $next)
    {
        $this->recordRequestLog();

        $response = $next($request);

        $this->recordResponseLog($response);

        return $response;
    }

    protected function recordRequestLog()
    {
        $header = request()->header();
        $logShowToken = config('logging.show_token');
        if (!$logShowToken && !empty($header['authorization'])) {
            $header['authorization'] = '******';
        }
        unset($header['cookie']);

//        Log::info('请求信息', [
//            "url" => request()->fullUrl(),
//            "uri" => request()->getUri(),
//            "method" => request()->method(),
//            "ip" => request()->getClientIp(),
//            "header" => json_encode($header, JSON_UNESCAPED_UNICODE),
//            "getParams" => json_encode(request()->query(), JSON_UNESCAPED_UNICODE),
//            "postParams" => json_encode(request()->post(), JSON_UNESCAPED_UNICODE),
//        ]);
    }

    /**
     * @param $response \Illuminate\Http\Response
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2024/12/15
     */
    protected function recordResponseLog($response)
    {
        $data = $response->getContent();
        $data = json_decode($data, true);

        if (Route::currentRouteName() === 'login') {
            $logShowToken = config('logging.show_token');
            if (!$logShowToken) {
                $data['data']['token'] = '******';
            }
        }
//        Log::info("返回信息", [
//            'content' => json_encode($data, JSON_UNESCAPED_UNICODE),
//        ]);
    }
}
